package common

import (
	"MoSkeleton/framework/core/consts"
	"MoSkeleton/framework/core/dto/response"
	"MoSkeleton/framework/core/moerrors"
	"MoSkeleton/framework/utils"
	"MoSkeleton/global"
	"MoSkeleton/services"
	"errors"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"path/filepath"
)

type CommonCtrl struct {
}

// UploadFile 上传文件
// @Tags 公共
// @Summary 上传文件
// @Description 上传文件
// @Security ApiKeyAuth
// @Param file formData file true "文件"
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "{"code": 200, "data": [...],"msg": "ok"}"
// @Router /common/upload [post]
func (cc *CommonCtrl) UploadFile(c *gin.Context) {
	file, err := utils.GinLimitUploadFileSize(c, "file", global.ConfigContainerInst.AppConfig.App.Gin.Multipart.MaxFileSize)
	if err != nil {
		if errors.Is(err, new(moerrors.ValidateMsgError)) {
			response.FailValidateError(c, err.(*moerrors.ValidateMsgError))
		} else {
			response.FailMsg(c, consts.FilesUploadFailCode, "上传文件失败")
		}
		return
	}
	if browserUploadFile, err := services.ServiceGroupInst.CommonGroupInst.CommonServiceInst.UploadFile(file); err != nil {
		global.MoLogger.Error("上传文件失败", zap.Error(err))
		response.FailMsg(c, consts.ServerOccurredErrorCode, "上传文件失败")
		return
	} else {
		result := make(map[string]interface{})
		result["url"] = browserUploadFile
		result["fileName"] = browserUploadFile
		result["newFileName"] = filepath.Base(browserUploadFile)
		result["originalFilename"] = file.Filename
		response.Success(c, "上传文件成功", result)
		return
	}
}
